using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace Updater
{
    public partial class MainForm : Form
    {
        private UpdateHelper _updateHelper;
        private string _updateFilePath;
        private string _targetExePath;
        private string _targetAppPath;

        public MainForm(string[] args)
        {
            InitializeComponent();
            ParseArguments(args);
        }

        private void ParseArguments(string[] args)
        {
            // 解析命令行参数
            // 格式: Updater.exe /updateFile:"更新文件路径" /targetExe:"目标程序路径" /targetApp:"目标应用路径"
            foreach (string arg in args)
            {
                if (arg.StartsWith("/updateFile:"))
                {
                    _updateFilePath = arg.Substring("/updateFile:".Length);
                }
                else if (arg.StartsWith("/targetExe:"))
                {
                    _targetExePath = arg.Substring("/targetExe:".Length);
                }
                else if (arg.StartsWith("/targetApp:"))
                {
                    _targetAppPath = arg.Substring("/targetApp:".Length);
                }
            }

            // 如果没有提供参数，使用默认值
            if (string.IsNullOrEmpty(_updateFilePath))
            {
                _updateFilePath = Path.Combine(Application.StartupPath, "update.zip");
            }

            if (string.IsNullOrEmpty(_targetExePath))
            {
                _targetExePath = Path.Combine(Application.StartupPath, "..", "SoftManager.exe");
            }

            if (string.IsNullOrEmpty(_targetAppPath))
            {
                _targetAppPath = Path.Combine(Application.StartupPath, "..");
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // 设置窗口位置在右下角
            Rectangle screenArea = Screen.GetWorkingArea(this);
            this.Location = new Point(screenArea.Width - this.Width - 20, screenArea.Height - this.Height - 20);
            
            // 初始化界面
            lblStatus.Text = "准备更新...";
            progressBar.Value = 0;

            // 创建更新帮助类
            _updateHelper = new UpdateHelper(_updateFilePath, _targetExePath, _targetAppPath);
            _updateHelper.UpdateProgress += UpdateHelper_UpdateProgress;
            _updateHelper.UpdateCompleted += UpdateHelper_UpdateCompleted;

            // 开始更新
            _updateHelper.StartUpdate();
        }

        private void UpdateHelper_UpdateProgress(object sender, UpdateProgressEventArgs e)
        {
            // 更新进度条和状态文本
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateHelper_UpdateProgress(sender, e)));
                return;
            }

            progressBar.Value = e.ProgressPercentage;
            lblStatus.Text = e.StatusMessage;
        }

        private void UpdateHelper_UpdateCompleted(object sender, UpdateCompletedEventArgs e)
        {
            // 更新完成
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateHelper_UpdateCompleted(sender, e)));
                return;
            }

            if (e.Result.Success)
            {
                MessageBox.Show("更新成功！", "更新完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                StartTargetApplication();
            }
            else
            {
                MessageBox.Show(e.Result.Message, "更新失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // 关闭更新程序
            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            // 取消更新
            if (_updateHelper != null)
            {
                _updateHelper.CancelUpdate();
            }
        }

        /// <summary>
        /// 启动目标应用程序
        /// </summary>
        private void StartTargetApplication()
        {
            try
            {
                if (File.Exists(_targetExePath))
                {
                    Process.Start(_targetExePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动应用程序失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}